<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 后台通用方法
class Yt extends BaseController {
    // 定时开关机v2
    private $powerTimeV2Name = 'brand_power_time_v2';

	public function __construct() {
        parent::__construct();
    }

    // 同步银通学校数据
    public function update_yt_school($schoolId) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // $this->load->model('dataModel');
        $this->load->model('configModel');
        $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if($schoolInfo['school_from'] != X_DATA_YINTONG) throw new Exception("该学校不是来自银通系统，数据同步失败");

        // 请求银通接口
        include_once(APPPATH. "libraries/YinTong.php");
        $this->yintong = new YinTong($schoolInfo['school_x_id'], $schoolInfo['school_x_params'], $schoolInfo['school_x_token']);
        // echo '<pre>';var_export($dataArr);exit;
        // // 只获取后两级作为：年级，班级
        // $deptDataArr = $this->get_dept_data();
        // $deptArr= $deptDataArr['data'];
        // $level = $deptDataArr['level'];
        // if($level < 2) {
        //     throw new Exception("接口数据层级小于2");
        // }
        // $gradeDataArr = $this->get_dept_level_data($deptArr, $level - 1);
        // $classDataArr = $this->get_dept_level_data($deptArr, $level);
        $dataArr = $this->get_dept_grade_and_class_data();
        if(empty($dataArr['grade']) || empty($dataArr['class'])) {
            throw new Exception("部门接口数据错误");
        }
        $gradeDataArr = $dataArr['grade'];
        $classDataArr = $dataArr['class'];
        // echo json_encode($classDataArr);exit;
        // echo json_encode($level);exit;
        // 同步年级数据接口
        $this->_update_yt_grade_data($schoolInfo, $gradeDataArr);
        // 同步课室数据接口
        $this->_update_yt_classroom_data($schoolInfo, $classDataArr);
        // 同步班级数据接口
        $this->_update_yt_class_data($schoolInfo, $classDataArr);
        // 同步学生数据接口
        $this->_update_yt_student_data($schoolInfo);
        // 同步学生照片数据接口
        // $this->_update_yt_student_photo_data($schoolInfo);

        // 更新时间
        $update['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolTable, $update, "id='{$schoolId}'");
        exit(json("同步数据成功", true));
    }

    // 学生数据量大，分页请求
    public function update_yt_school_student() {
        // 加载数据库类
        $this->load->model('schoolModel');
        $jsonData = file_get_contents('php://input');
        $dataArr = json_decode($jsonData, true);
        if(isset($dataArr['action']) && $dataArr['action'] == 'update') {
            if($dataArr['data']) {
                $this->db->update_batch(SchoolModel::$schoolStudentTable, $dataArr['data'], "x_unique_id");
            }
        }
        if(isset($dataArr['action']) && $dataArr['action'] == 'insert') {
            if($dataArr['data']) {
                $this->db->insert_batch(SchoolModel::$schoolStudentTable, $dataArr['data']);
            }
        }
    }

    // 同步银通年级接口
    private function _update_yt_grade_data($schoolInfo, $gradeDataArr) {
        // 不分校区
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$gradeTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolInfo['id'];
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        // 获取默认校区
        $campusParams['isDelete'] = 0;
        $campusParams['schoolId'] = $schoolInfo['id'];
        $campusArr = $this->schoolModel->get_campus_list($campusParams);
        if($campusArr) {
            $defaultCampusId = $campusArr[0]['id'];
        } else {
            $defaultCampusId = 0;
        }
        //获取全部行政班信息接口
        $insertGradeBatch = $updateGradeBatch = array();
        foreach($gradeDataArr as $item) {
            // 最上级为年级
            $gradeId = $item['deptid'];
            // 设置年级数组
            $gradeData['school_id'] = $schoolInfo['id'];
            $gradeData['x_grade_id'] = $gradeId;
            $gradeData['campus_id'] = $defaultCampusId;        // 设置校区id
            // 自己做一个唯一ID
            $gradeData['x_unique_id'] = $schoolInfo['id']. "_". $defaultCampusId. "_". $gradeId;
            $gradeData['grade_name'] = $item['deptname'];
            $gradeData['is_delete'] = 0;
            $gradeData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($gradeList[$gradeId])) {
                $updateGradeBatch[$gradeId] = $gradeData;
            } else {
                $gradeData['createtime'] = $gradeData['updatetime'];
                $insertGradeBatch[$gradeId] = $gradeData;
            }
        }
        if(count($insertGradeBatch)) $this->db->insert_batch(ClassesModel::$gradeTable, $insertGradeBatch);
        if(count($updateGradeBatch)) $this->db->update_batch(ClassesModel::$gradeTable, $updateGradeBatch, "x_unique_id");
        
    }

    // 同步银通课室接口（班级与课室一一对应，用班级名作为课室名）
    private function _update_yt_classroom_data($schoolInfo, $classDataArr) {
        // 不分校区
        // 将全部班级数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$classroomTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        // 获取默认校区
        $campusParams['isDelete'] = 0;
        $campusParams['schoolId'] = $schoolInfo['id'];
        $campusArr = $this->schoolModel->get_campus_list($campusParams);
        if($campusArr) {
            $defaultCampusId = $campusArr[0]['id'];
        } else {
            $defaultCampusId = 0;
        }
        // 获取本校全部课室
        $roomParams['schoolId'] = $schoolInfo['id'];
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'x_classroom_id');
        // 遍历接口所有数据
        $insertRoomBatch = $updateRoomBatch = array();
        foreach($classDataArr as $item) {
            $locationsId = $item['deptid'];
            // if(!$locationsId || $locationsId == 'null') continue;

            $roomData['school_id'] = $schoolInfo['id'];
            $roomData['x_classroom_id'] = $locationsId;
            $roomData['campus_id'] = $defaultCampusId;             // 设置校区ID
            // 自己做一个唯一ID
            $roomData['x_unique_id'] = $schoolInfo['id']. "_". $defaultCampusId. "_". $locationsId;
            $roomData['classroom_name'] = $item['deptname'];
            $roomData['is_delete'] = 0;
            $roomData['updatetime'] = date("Y-m-d H:i:s");
            // 更新还是新增
            if(isset($roomList[$locationsId])) {
                $updateRoomBatch[] = $roomData;
            } else {
                $roomData['createtime'] = $roomData['updatetime'];
                $insertRoomBatch[] = $roomData;
            }
        }
        if(count($insertRoomBatch)) $this->db->insert_batch(ClassesModel::$classroomTable, $insertRoomBatch);
        if(count($updateRoomBatch)) $this->db->update_batch(ClassesModel::$classroomTable, $updateRoomBatch, "x_unique_id");
    }

    // 同步银通班级接口
    private function _update_yt_class_data($schoolInfo, $classDataArr) {
        // 不分校区
        // 将全部班级数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$classTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        // 获取默认校区
        $campusParams['isDelete'] = 0;
        $campusParams['schoolId'] = $schoolInfo['id'];
        $campusArr = $this->schoolModel->get_campus_list($campusParams);
        if($campusArr) {
            $defaultCampusId = $campusArr[0]['id'];
        } else {
            $defaultCampusId = 0;
        }
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolInfo['id'];
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        // 获取本校全部班级
        $classParams['schoolId'] = $schoolInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        // 获取本校全部课室
        $roomParams['schoolId'] = $schoolInfo['id'];
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'x_classroom_id');
        //获取全部行政班信息接口
        $insertClassBatch = $updateClassBatch = array();
        foreach($classDataArr as $item) {
            if(!isset($gradeList[$item['pdeptid']])) {
                continue;
            }
            $classData['school_id'] = $schoolInfo['id'];
            $classData['campus_id'] = $defaultCampusId; // 设置校区id
            $classData['grade_id'] = $gradeList[$item['pdeptid']]['id'];
            $classData['x_class_id'] = $item['deptid'];
            // 自己做一个唯一ID
            $classData['x_unique_id'] = $schoolInfo['id']. "_". $defaultCampusId . "_". $item['deptid'];
            $classData['classroom_id'] = isset($roomList[$item['deptid']]) ? $roomList[$item['deptid']]['id'] : 0;
            $classData['class_name'] = $item['deptname'];
            // 如果有班主任
            // $classData['class_master'] = (isset($item['classTeacher']) && $item['classTeacher'] && isset($item['classTeacher']['teacherEID']) && isset($teacherList[$item['classTeacher']['teacherEID']])) ? $teacherList[$item['classTeacher']['teacherEID']]['id'] : 0;
            $classData['class_type'] = CLASSES_TYPE_NORMAL;
            $classData['is_delete'] = 0;
            $classData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($classList[$item['deptid']])) {
                $updateClassBatch[] = $classData;
            } else {
                $classData['createtime'] = $classData['updatetime'];
                $insertClassBatch[] = $classData;
            }
        }
        if(count($insertClassBatch)) $this->db->insert_batch(ClassesModel::$classTable, $insertClassBatch);
        if(count($updateClassBatch)) $this->db->update_batch(ClassesModel::$classTable, $updateClassBatch, "x_unique_id");
    }

    // 同步银通学生接口
    private function _update_yt_student_data($schoolInfo) {
        $result = $this->yintong->get_user_list();
        if($result == false || $result['code'] !== '0000') {
            throw new Exception('请求银通‘人员信息同步接口’出现错误');
        }
        $resultArr = json_decode($result['data'], true);
        if($resultArr['status'] != 0) {
            throw new Exception('请求银通‘人员信息同步接口’出现错误');
        }
        $apiDataArr = $resultArr['data_arr'];
        // echo '<pre>';var_export($apiDataArr);exit;

        // 不分校区
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $deleteState['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolStudentTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        
        // 获取本校全部学生
        $studentParams['schoolId'] = $schoolInfo['id'];
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'x_student_id');
        // 获取行政班
        $classParams['schoolId'] = $schoolInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        // 获取接口学生
        $insertStudentBatch = $updateStudentBatch = array();
        $defaultPwd = password_hash(123456, PASSWORD_DEFAULT);
        foreach($apiDataArr as $item) {
            // 只取班级所属人员
            // cardstatus=3，即卡注销，删除该学生
            if(isset($classList[$item['deptid']]) && $item['cardstatus'] !== 3) {
                $studentData['is_delete'] = 0;
                $studentData['school_id'] = $schoolInfo['id'];
                $studentData['campus_id'] = $classList[$item['deptid']]['campus_id'];      // 设置校区ID
                $studentData['x_student_id'] = $item['custcode'];  // 对应银通人员唯一编号
                $studentData['username'] = $item['workno'] ? $item['workno'] : '';        // 对应银通学号
                $studentData['realname'] = $item['custname'] ? $item['custname'] : $item['workno'];

                // $studentData['realcard'] = $item['cardno'] ? $item['cardno'] : '';

                // 判断卡状态
                if($item['status'] === 1 && $item['cardstatus'] === 0) {
                    // 16进制转换成10进制
                    $studentData['realcard'] = $item['cardno'] ? hexdec($item['cardno']) : '';
                } else {
                    $studentData['realcard'] = '';
                }

                // 自己做一个唯一ID
                $studentData['x_unique_id'] = $schoolInfo['id']. "_". $classList[$item['deptid']]['campus_id'] . "_". $item['custcode'];

                $studentData['class_id'] = $classList[$item['deptid']]['id'];
                
                $studentData['gender'] = '男'; // 默认男
                $studentData['headimgurl'] = UP_URL. "default/boy.jpg"; // 默认男头像
                $studentData['mobile'] = $item['phone'] ? $item['phone'] : '';
                $studentData['updatetime'] = date("Y-m-d H:i:s");

                if(isset($studentList[$item['custcode']])) {
                    $updateStudentBatch[] = $studentData;
                } else {
                    $studentData['password'] = $defaultPwd;
                    $studentData['createtime'] = $studentData['updatetime'];
                    $insertStudentBatch[] = $studentData;
                }
            }

          
        }
        // echo '<pre>';var_export($insertStudentBatch);exit;
        // if(count($insertStudentBatch)) $this->db->insert_batch(SchoolModel::$schoolStudentTable, $insertStudentBatch);
        // if(count($updateStudentBatch)) $this->db->update_batch(SchoolModel::$schoolStudentTable, $updateStudentBatch, "x_unique_id");

        // 分页处理
        if(count($insertStudentBatch)) {
            if(count($insertStudentBatch) > 5000) {
                // 每页5000条
                $tempArr = array_chunk($insertStudentBatch, 5000);
                // 分页请求
                foreach($tempArr as $item) {
                    $dataArr = array(
                        'action' => 'insert',
                        'data' => $item
                    );
                    $url = admin_url('yt/update_yt_school_student');
                    $this->send_post($url, json_encode($dataArr, JSON_UNESCAPED_UNICODE));
                }
            } else {
                $this->db->insert_batch(SchoolModel::$schoolStudentTable, $insertStudentBatch);
            }
        }
        if(count($updateStudentBatch)) {
            if(count($updateStudentBatch) > 5000) {
                // 每页5000条
                $tempArr = array_chunk($updateStudentBatch, 5000);
                // 分页请求
                foreach($tempArr as $item) {
                    $dataArr = array(
                        'action' => 'update',
                        'data' => $item
                    );
                    $url = admin_url('yt/update_yt_school_student');
                    $this->send_post($url, json_encode($dataArr, JSON_UNESCAPED_UNICODE));
                }
            } else {
                $this->db->update_batch(SchoolModel::$schoolStudentTable, $updateStudentBatch, "x_unique_id");
            }
        }   
    }

    // 同步银通学生照片接口
    private function _update_yt_student_photo_data($schoolInfo) {
        // 获取本校全部学生
        $studentParams['schoolId'] = $schoolInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'x_student_id');

        foreach($studentList as $student) {
            // 200701000004
            $result = $this->yintong->get_user_photo_list($student['x_student_id']);
            if($result == false || $result['code'] !== '0000') {
                throw new Exception('请求银通‘人员照片同步接口’出现错误');
            }
            $resultArr = json_decode($result['data'], true);
            if($resultArr['status'] != 0) {
                throw new Exception('请求银通‘人员照片同步接口’出现错误');
            }
            // $apiDataArr = $resultArr['data_arr'];
            $photo = $resultArr['photo'];
            // echo '<pre>';var_export($photo);exit;
    
            if($photo) {
                $imageBase64 = 'data:image/png;base64,' . $photo ;
                // 写入图片
                require_once('vendor/autoload.php');
                $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".jpg";
                $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
                $client = new Upyun\Upyun($serviceConfig);
                $signImg = UP_URL. $fileName;
                try{
                    $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
                } catch(Exception $e) {
                    // 捕获同个图片名，上传多次报错
                    // $signImg = $e->getMessage();
                    throw new Exception("429 Too Many Requests");
                }
                if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");

                var_export($signImg);
            }
        
        }
        exit;

        // 获取本校全部学生
        $studentParams['schoolId'] = $schoolInfo['id'];
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'x_student_id');

        
    }
    
    // 按层级排好的部门结构
    private function get_dept_data() {
        $result = $this->yintong->get_dept_list();
        //    echo '<pre>';var_export($result);exit;
        if($result == false || $result['code'] !== '0000') {
            throw new Exception('请求银通‘部门信息同步接口’出现错误');
        }
        $resultArr = json_decode($result['data'], true);
        if($resultArr['status'] != 0) {
            throw new Exception('请求银通‘部门信息同步接口’出现错误');
        }
        $apiDataArr = $resultArr['data_arr'];
        // $apiDataArr[] = array(
        //     "deptid" => 1001,
        //     "deptname" => "高2017级1班1组",
        //     "pdeptid" => 401
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 1002,
        //     "deptname" => "高2017级1班2组",
        //     "pdeptid" => 401
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 1003,
        //     "deptname" => "高2017级2班2组",
        //     "pdeptid" => 402
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 10001,
        //     "deptname" => "高2017级1班1组（1）",
        //     "pdeptid" => 1001
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 10002,
        //     "deptname" => "高2017级1班1组（2）",
        //     "pdeptid" => 1001
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 100001,
        //     "deptname" => "高2017级1班1组（1）（1）",
        //     "pdeptid" => 10001
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 100002,
        //     "deptname" => "高2017级1班1组（1）（2）",
        //     "pdeptid" => 10001
        // );
        $deptArr = array();  // 排完序的数组
        $deptLevel = 0; // 层级
        // 第一级
        foreach($apiDataArr as $apiData) {
            // 获取父节点
            if($apiData['pdeptid'] == -1) {
                $deptArr[$apiData['deptid']] = $apiData;
                $deptLevel = 1;
            }
        }
        // 第二级
        foreach($apiDataArr as $apiData) {
            foreach($deptArr as $key => $dept) {
                if($key == $apiData['pdeptid']) {
                    $deptArr[$key]['child'][$apiData['deptid']] = $apiData;
                    $deptLevel = 2;
                }
            }
        }
        // 第三级
        foreach($apiDataArr as $apiData) {
            foreach($deptArr as $key => $dept) {
                if(isset($dept['child'])) {
                    foreach($dept['child'] as $key2 => $dept2) {
                        if($key2 == $apiData['pdeptid']) {
                            $deptArr[$key]['child'][$key2]['child'][$apiData['deptid']] = $apiData;
                            $deptLevel = 3;
                        }
                    }
                }
            }
        }
        // 第四级
        foreach($apiDataArr as $apiData) {
            foreach($deptArr as $key => $dept) {
                if(isset($dept['child'])) {
                    foreach($dept['child'] as $key2 => $dept2) {
                        if(isset($dept2['child'])) {
                            foreach($dept2['child'] as $key3 => $dept3) {
                                if($key3 == $apiData['pdeptid']) {
                                    $deptArr[$key]['child'][$key2]['child'][$key3]['child'][$apiData['deptid']] = $apiData;
                                    $deptLevel = 4;
                                }
                            }
                        }
                    }
                }
            }
        }
        // 第五级
        foreach($apiDataArr as $apiData) {
            foreach($deptArr as $key => $dept) {
                if(isset($dept['child'])) {
                    foreach($dept['child'] as $key2 => $dept2) {
                        if(isset($dept2['child'])) {
                            foreach($dept2['child'] as $key3 => $dept3) {
                                if(isset($dept3['child'])) {
                                    foreach($dept3['child'] as $key4 => $dept4) {
                                        if($key4 == $apiData['pdeptid']) {
                                            $deptArr[$key]['child'][$key2]['child'][$key3]['child'][$key4]['child'][$apiData['deptid']] = $apiData;
                                            $deptLevel = 5;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // 第六级
        foreach($apiDataArr as $apiData) {
            foreach($deptArr as $key => $dept) {
                if(isset($dept['child'])) {
                    foreach($dept['child'] as $key2 => $dept2) {
                        if(isset($dept2['child'])) {
                            foreach($dept2['child'] as $key3 => $dept3) {
                                if(isset($dept3['child'])) {
                                    foreach($dept3['child'] as $key4 => $dept4) {
                                        if(isset($dept4['child'])) {
                                            foreach($dept4['child'] as $key5 => $dept5) {
                                                if($key5 == $apiData['pdeptid']) {
                                                    $deptArr[$key]['child'][$key2]['child'][$key3]['child'][$key4]['child'][$key5]['child'][$apiData['deptid']] = $apiData;
                                                    $deptLevel = 6;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return array(
            'level' => $deptLevel,
            'data' => $deptArr
        );
        // echo json_encode($deptArr);exit;
    }
    // 获取第几层级
    private function get_dept_level_data($deptDataArr, $level) {
        $dataArr = array();
        foreach($deptDataArr as $deptData1) {
            if($level == 1) {
                $dataArr[] = $deptData1;
            } else {
                if(isset($deptData1['child'])) {
                    foreach($deptData1['child'] as $deptData2) {
                        if($level == 2) {
                            $dataArr[] = $deptData2;
                        } else {
                            if(isset($deptData2['child'])) {
                                foreach($deptData2['child'] as $deptData3) {
                                    if($level == 3) {
                                        $dataArr[] = $deptData3;
                                    } else {
                                        if(isset($deptData3['child'])) {
                                            foreach($deptData3['child'] as $deptData4) {
                                                if($level == 4) {
                                                    $dataArr[] = $deptData4;
                                                } else {
                                                    if(isset($deptData4['child'])) {
                                                        foreach($deptData4['child'] as $deptData5) {
                                                            if($level == 5) {
                                                                $dataArr[] = $deptData5;
                                                            } else {
                                                                if(isset($deptData5['child'])) {
                                                                    foreach($deptData5['child'] as $deptData6) {
                                                                        if($level == 6) {
                                                                            $dataArr[] = $deptData6;
                                                                        }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } 
                            }
                        }

                        } 
                    }
                }
            }
        }
        return $dataArr;
    }

    // 最后一层为班级，后二层为年级
    private function get_dept_grade_and_class_data() {
        $result = $this->yintong->get_dept_list();
        //    echo '<pre>';var_export($result);exit;
        if($result == false || $result['code'] !== '0000') {
            throw new Exception('请求银通‘部门信息同步接口’出现错误');
        }
        $resultArr = json_decode($result['data'], true);
        if($resultArr['status'] != 0) {
            throw new Exception('请求银通‘部门信息同步接口’出现错误');
        }
        $apiDataArr = $resultArr['data_arr'];
        // $apiDataArr[] = array(
        //     "deptid" => 1001,
        //     "deptname" => "高2017级1班1组",
        //     "pdeptid" => 401
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 1002,
        //     "deptname" => "高2017级1班2组",
        //     "pdeptid" => 401
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 1003,
        //     "deptname" => "高2017级2班2组",
        //     "pdeptid" => 402
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 10001,
        //     "deptname" => "高2017级1班1组（1）",
        //     "pdeptid" => 1001
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 10002,
        //     "deptname" => "高2017级1班1组（2）",
        //     "pdeptid" => 1001
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 100001,
        //     "deptname" => "高2017级1班1组（1）（1）",
        //     "pdeptid" => 10001
        // );
        // $apiDataArr[] = array(
        //     "deptid" => 100002,
        //     "deptname" => "高2017级1班1组（1）（2）",
        //     "pdeptid" => 10001
        // );
        // 不是作为父节点的即是最后一级
        $pdeptidArr = array_value_to_key($apiDataArr, 'pdeptid');
        $classDeptArr = array();
        foreach($apiDataArr as $apiData) {
            // 排除pdeptid = -1
            if(!isset($pdeptidArr[$apiData['deptid']]) && $apiData['pdeptid'] != -1) {
                $classDeptArr[] = $apiData;
            }
        }
        // 通过classdeptarr的父id获取年级数据
        $gradeDeptArr = array();
        $gradePdeptidArr = array_value_to_key($classDeptArr, 'pdeptid');  // 年级id组合
        foreach($apiDataArr as $apiData) {
         
            if(isset($gradePdeptidArr[$apiData['deptid']])) {
                $gradeDeptArr[] = $apiData;
            }
        }
        $res = array(
            'grade' => $gradeDeptArr,
            'class' => $classDeptArr
        );
        return $res;
        // echo json_encode($res);exit;
    }

    // 判断是否分校区
    private function get_muti_campus($schoolId) {
        $mutiCampusArr = $this->configModel->get_school_config($schoolId, 'muti_campus');
        if($mutiCampusArr) {
            $mutiCampus = $mutiCampusArr['config_value'];
        } else {
            $mutiCampus = 0;   
        }
        return $mutiCampus;
    }

    // 提交数据到服务器
    private function send_post($url, $data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 发送json类型的header
        $header = array("Content-Type: application/json");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $tmpInfo = curl_exec($ch);

        if(curl_errno($ch)) return curl_error($ch);
        curl_close($ch);
        return $tmpInfo;
    }

   // // 同步银通年级接口（备份）
    // private function _update_yt_grade_data($schoolInfo) {
    //     $result = $this->yintong->get_dept_list();
    //         //    echo '<pre>';var_export($result);exit;
    //     if($result == false || $result['code'] !== '0000') {
    //         throw new Exception('请求银通‘部门信息同步接口’出现错误');
    //     }
    //     $resultArr = json_decode($result['data'], true);
    //     if($resultArr['status'] != 0) {
    //         throw new Exception('请求银通‘部门信息同步接口’出现错误');
    //     }
    //     $apiDataArr = $resultArr['data_arr'];
    //     echo '<pre>';var_export($apiDataArr);exit;

    //     // 判断是否分校区
    //     $mutiCampus = $this->get_muti_campus($schoolInfo['id']);
    //     if($mutiCampus) {
    //         // 分校区
    //         // 测试分校区数据
    //         // $apiDataArr = array (
    //         //     0 => 
    //         //     array (
    //         //     'deptid' => 1,
    //         //     'deptname' => '校区1',
    //         //     'pdeptid' => -1,
    //         //     ),
    //         //     1 => 
    //         //     array (
    //         //     'deptid' => 2,
    //         //     'deptname' => '校区2',
    //         //     'pdeptid' => -1,
    //         //     ),
    //         //     2 => 
    //         //     array (
    //         //     'deptid' => 3,
    //         //     'deptname' => '校区3',
    //         //     'pdeptid' => -1,
    //         //     ),
    //         //     3 => 
    //         //     array (
    //         //     'deptid' => 4,
    //         //     'deptname' => '年级1',
    //         //     'pdeptid' => 1,
    //         //     ),
    //         //     4 => 
    //         //     array (
    //         //     'deptid' => 5,
    //         //     'deptname' => '年级2',
    //         //     'pdeptid' => 2,
    //         //     ),
    //         //     5 => 
    //         //     array (
    //         //     'deptid' => 6,
    //         //     'deptname' => '年级3',
    //         //     'pdeptid' => 3,
    //         //     ),
    //         //     6 => 
    //         //     array (
    //         //     'deptid' => 7,
    //         //     'deptname' => '班级1',
    //         //     'pdeptid' => 4,
    //         //     ),
    //         //     7 => 
    //         //     array (
    //         //     'deptid' => 8,
    //         //     'deptname' => '班级2',
    //         //     'pdeptid' => 5,
    //         //     ),
    //         //     8 => 
    //         //     array (
    //         //     'deptid' => 9,
    //         //     'deptname' => '班级3',
    //         //     'pdeptid' => 6,
    //         //     ),
    //         //     9 => 
    //         //     array (
    //         //     'deptid' => 10,
    //         //     'deptname' => '班级4',
    //         //     'pdeptid' => 6,
    //         //     ),
    //         //     10 => 
    //         //     array (
    //         //     'deptid' => 11,
    //         //     'deptname' => '班级5',
    //         //     'pdeptid' => 6,
    //         //     ),
    //         // );

    //         // 将全部校区数据设置为已删除状态
    //         $deleteState['is_delete'] = 1;
    //         $this->db->update(SchoolModel::$campusTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
    //         // 获取本校全部校区
    //         $campusParams['schoolId'] = $schoolInfo['id'];
    //         $campusList = $this->schoolModel->get_campus_list($campusParams);
    //         $campusList = array_value_to_key($campusList, 'x_campus_id');
    //         $insertCampusBatch = $updateCampusBatch = array();
    //         foreach($apiDataArr as $item) {
    //             if($item['pdeptid'] == -1) {
    //                 // 最上级为年级
    //                 $campusId = $item['deptid'];
    //                 // 设置年级数组
    //                 $campusData['school_id'] = $schoolInfo['id'];
    //                 $campusData['x_campus_id'] = $campusId;
    //                 $campusData['campus_name'] = $item['deptname'];
    //                 $campusData['is_delete'] = 0;
    //                 $campusData['updatetime'] = date("Y-m-d H:i:s");
    //                 if(isset($campusList[$campusId])) {
    //                     $updateCampusBatch[$campusId] = $campusData;
    //                 } else {
    //                     $campusData['createtime'] = $campusData['updatetime'];
    //                     $insertCampusBatch[$campusId] = $campusData;
    //                 }
    //             }
    //         }
    //         if(count($insertCampusBatch)) $this->db->insert_batch(SchoolModel::$campusTable, $insertCampusBatch);
    //         if(count($updateCampusBatch)) $this->db->update_batch(SchoolModel::$campusTable, $updateCampusBatch, "x_campus_id");

    //         // 如未设置定时开关机，设置默认时间
    //         $campusParams['is_delete'] = 0;
    //         $campusParams['schoolId'] = $schoolInfo['id'];
    //         $campusList = $this->schoolModel->get_campus_list($campusParams);
    //         foreach($campusList as $campus) {
    //             // 获取开关机配置
    //             $powerTimeV2Config = $this->configModel->get_school_campus_config($schoolInfo['id'], $campus['id'], $this->powerTimeV2Name);
    //             // 如未设置
    //             if(empty($powerTimeV2Config)) {
    //                 // 默认周一到5开机，5:00-19:00
    //                 $powerTimeV2Json = $this->_get_default_power_time_v2_json();
    //                 $this->configModel->save_school_campus_config($schoolInfo['id'], $campus['id'], $this->powerTimeV2Name, $powerTimeV2Json);
    //             }
    //         }

    //         // 获取本校全部校区
    //         $campusParams['schoolId'] = $schoolInfo['id'];
    //         $campusParams['isDelete'] = 0;
    //         $campusList = $this->schoolModel->get_campus_list($campusParams);
    //         $campusList = array_value_to_key($campusList, 'x_campus_id');

    //         // 将全部年级数据设置为已删除状态
    //         $deleteState['is_delete'] = 1;
    //         $this->db->update(ClassesModel::$gradeTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
    //         // 获取本校全部年级
    //         $gradeParams['schoolId'] = $schoolInfo['id'];
    //         $gradeList = $this->classesModel->get_grade_list($gradeParams);
    //         $gradeList = array_value_to_key($gradeList, 'x_grade_id');
    //         $insertGradeBatch = $updateGradeBatch = array();
    //         foreach($apiDataArr as $item) {
    //             if(isset($campusList[$item['pdeptid']])) {
    //                 // 最上级为年级
    //                 $gradeId = $item['deptid'];
    //                 // 设置年级数组
    //                 $gradeData['school_id'] = $schoolInfo['id'];
    //                 $gradeData['x_grade_id'] = $gradeId;
    //                 $gradeData['campus_id'] = $campusList[$item['pdeptid']]['id'];        // 设置校区id
    //                 // 自己做一个唯一ID
    //                 $gradeData['x_unique_id'] = $schoolInfo['id']. "_". $campusList[$item['pdeptid']]['id']. "_". $gradeId;
    //                 $gradeData['grade_name'] = $item['deptname'];
    //                 $gradeData['is_delete'] = 0;
    //                 $gradeData['updatetime'] = date("Y-m-d H:i:s");
    //                 if(isset($gradeList[$gradeId])) {
    //                     $updateGradeBatch[$gradeId] = $gradeData;
    //                 } else {
    //                     $gradeData['createtime'] = $gradeData['updatetime'];
    //                     $insertGradeBatch[$gradeId] = $gradeData;
    //                 }
    //             }
    //         }
    //         if(count($insertGradeBatch)) $this->db->insert_batch(ClassesModel::$gradeTable, $insertGradeBatch);
    //         if(count($updateGradeBatch)) $this->db->update_batch(ClassesModel::$gradeTable, $updateGradeBatch, "x_unique_id");
    //     } else {
    //         // 不分校区
    //         // 将全部数据设置为已删除状态
    //         $deleteState['is_delete'] = 1;
    //         $this->db->update(ClassesModel::$gradeTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
    //         // 获取本校全部年级
    //         $gradeParams['schoolId'] = $schoolInfo['id'];
    //         $gradeList = $this->classesModel->get_grade_list($gradeParams);
    //         $gradeList = array_value_to_key($gradeList, 'x_grade_id');
    //         // 获取默认校区
    //         $campusParams['isDelete'] = 0;
    //         $campusParams['schoolId'] = $schoolInfo['id'];
    //         $campusArr = $this->schoolModel->get_campus_list($campusParams);
    //         if($campusArr) {
    //             $defaultCampusId = $campusArr[0]['id'];
    //         } else {
    //             $defaultCampusId = 0;
    //         }

    //         //获取全部行政班信息接口
    //         $insertGradeBatch = $updateGradeBatch = array();
    //         foreach($apiDataArr as $item) {
    //             if($item['pdeptid'] == -1) {
    //                 // 最上级为年级
    //                 $gradeId = $item['deptid'];
    //                 // 设置年级数组
    //                 $gradeData['school_id'] = $schoolInfo['id'];
    //                 $gradeData['x_grade_id'] = $gradeId;
    //                 $gradeData['campus_id'] = $defaultCampusId;        // 设置校区id
    //                 // 自己做一个唯一ID
    //                 $gradeData['x_unique_id'] = $schoolInfo['id']. "_". $defaultCampusId. "_". $gradeId;
    //                 $gradeData['grade_name'] = $item['deptname'];
    //                 $gradeData['is_delete'] = 0;
    //                 $gradeData['updatetime'] = date("Y-m-d H:i:s");
    //                 if(isset($gradeList[$gradeId])) {
    //                     $updateGradeBatch[$gradeId] = $gradeData;
    //                 } else {
    //                     $gradeData['createtime'] = $gradeData['updatetime'];
    //                     $insertGradeBatch[$gradeId] = $gradeData;
    //                 }
    //             }
    //         }
    //         if(count($insertGradeBatch)) $this->db->insert_batch(ClassesModel::$gradeTable, $insertGradeBatch);
    //         if(count($updateGradeBatch)) $this->db->update_batch(ClassesModel::$gradeTable, $updateGradeBatch, "x_unique_id");
    //     }
    // }

}
